﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;


namespace DataToShow.FileSendAndReceive
{
    public class ProtocolHelper
    {

        private XmlNode fileNode;
        private XmlNode root;

        public ProtocolHelper(string protocol)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(protocol);
            root = doc.DocumentElement;
            fileNode = root.SelectSingleNode("file");
        }

        /// <summary>
        /// 此时的protocal一定为单条完整protocal
        /// </summary>
        /// <returns></returns>
        private FileRequestMode GetFileMode()
        {
            string mode = fileNode.Attributes["mode"].Value;
            mode = mode.ToLower();
            if (mode == "send")
                return FileRequestMode.Send;
            else
                return FileRequestMode.Receive;
        }

        /// <summary>
        /// 获取单条协议包含的信息
        /// </summary>
        /// <returns></returns>
        public FileProtocol GetProtocol()
        {
            FileRequestMode mode = GetFileMode();
            string fileName = "";
            int port = 0;

            fileName = fileNode.Attributes["name"].Value;
            port = Convert.ToInt32(fileNode.Attributes["port"].Value);

            return new FileProtocol(mode, port, fileName);
        }
        /// <summary>
        /// 枚举,代表是发送还是接收文件
        /// </summary>
        public enum FileRequestMode
        {
            Send = 0,
            Receive
        }
        /// <summary>
        /// 用来为整个协议字符串提供强类型的访问，注意这里覆盖了基类的ToString()方法，         
        //
        /// </summary>
        public struct FileProtocol
        {
            private readonly FileRequestMode mode;
            private readonly int port;
            private readonly string fileName;

            public FileProtocol
                (FileRequestMode mode, int port, string fileName)
            {
                this.mode = mode;
                this.port = port;
                this.fileName = fileName;
            }

            public FileRequestMode Mode
            {
                get { return mode; }
            }

            public int Port
            {
                get { return port; }
            }

            public string FileName
            {
                get { return fileName; }
            }

            public override string ToString()
            {
                return String.Format("<protocol><file name=\"{0}\" mode=\"{1}\" port=\"{2}\" /></protocol>",fileName, mode, port);
            }
        }
    }
}
